package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 新增员工
     *
     * @param employeeDTO 前端传来新增员工信息
     */
    @Override
    public void addEmp(EmployeeDTO employeeDTO) {
        //创建员工对象
        Employee employee = new Employee();
        //对象属性拷贝（只有拷贝的俩个对象的属性名一致才可以）
        BeanUtils.copyProperties(employeeDTO, employee);
        //设置默认密码123456，并将其加密
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //设置员工状态为启用
        employee.setStatus(StatusConstant.ENABLE);
        //补全属性 (这里不用了，用切面类补全了)
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //设置创建人ID和修改人ID
        //从ThreadLocal中取出登录人ID
        //Long empId = BaseContext.getCurrentId();
       // employee.setCreateUser(empId);
        //employee.setUpdateUser(empId);
        //调用Mapper新增员工
        employeeMapper.addEmp(employee);
    }

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        //对登录页面传来的密码进行MD5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 员工分页查询
     *
     * @param employeePageQueryDTO 前端传来查询参数
     * @return
     */
    @Override
    public PageResult queryAllEmp(EmployeePageQueryDTO employeePageQueryDTO) {
        //设置分页参数
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        //查询总条数
        List<Employee> employees = employeeMapper.queryAllEmp(employeePageQueryDTO);
        Page page =(Page) employees;
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 启用、禁用员工账号
     *
     * @param status 启用、禁用状态
     * @param id     要修改的员工ID
     */
    @Override
    public void updateEmpStatus(Integer status, Long id) {
        Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);
        employeeMapper.updateEmp(employee);
    }

    /**
     * 根据ID查询员工
     *
     * @param id
     * @return
     */
    @Override
    public EmployeeDTO queryEmpById(Long id) {
       EmployeeDTO employeeDTO = employeeMapper.queryEmpById(id);
       return employeeDTO;
    }

    /**
     * 修改员工
     *
     * @param employeeDTO
     */
    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {
        //创建员工对象
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.updateEmp(employee);
    }

    /**
     * 修改密码
     *
     * @param passwordEditDTO
     */
    @Override
    public void updateEmpPassword(PasswordEditDTO passwordEditDTO) {
        //获取修改者的ID
        Long empId = BaseContext.getCurrentId();
        passwordEditDTO.setEmpId(empId);
        //根据ID查询员工信息
        EmployeeDTO employeeDTO = employeeMapper.queryEmpById(empId);
        //对前端传来的旧密码加密
        String oldPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        //比对密码是否相同
        if (!oldPassword.equals(employeeDTO.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //如果相同，则将新密码加密后修改
        String newPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
        passwordEditDTO.setNewPassword(newPassword);
        employeeMapper.updateEmpPassword(passwordEditDTO);

    }


}
